 define(['jquery'], function ($) {
 	var app={
		//公共事件
		init:function(){
			//判断是否存在
		    $.isInArray=function(data,i,keyword){
		        var result=-1;//不存在返回-1
		        keyword=keyword.toLowerCase();//小写
		        $.each(data,function(key,value){
		            if(value[i].toLowerCase()==keyword){
		                result=key;//存在返回索引
		                return false;
		            }
		        });
		        return result;
		    };
		    $.setCookie=function(c_name,value,expiredays){
				var exdate=new Date()
				exdate.setDate(exdate.getDate()+expiredays)
				document.cookie=c_name+ "=" +escape(value)+
				((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
			}
			$.getCookie=function(c_name){
				if (document.cookie.length>0){
				  c_start=document.cookie.indexOf(c_name + "=")
				  if (c_start!=-1){ 
				    c_start=c_start + c_name.length+1 
				    c_end=document.cookie.indexOf(";",c_start)
				    if (c_end==-1) c_end=document.cookie.length
				    return unescape(document.cookie.substring(c_start,c_end))
				    } 
				}
				return ""
			}
			var _this=this;
			//搜索
			$(".searchBtn").on("click",function(evt){
				var obj=$(this).parent().find(".searchArea");
				var keyword=$.trim(obj.val());
				if(!$(".searchForm").hasClass('is_show')){
					$(".searchForm").addClass('is_show');
				}
				else if(keyword!=""){
					$(".searchForm").submit();
				}
			});
			$(".searchArea").on("focus",function(){
				var search_info=$(this).parent().parent();
				var value=$.trim($(this).val());
				if(value==""){
					_this.loadhistory(search_info);
				}
				else{
					if(search_info.find(".search_related_list li").size()>0){
						search_info.find(".search_related").fadeIn();
					}
				}
			});
			$(".search").on("click",function(event){
				var e = window.event ||event;
				if (e.stopPropagation) { 
					e.stopPropagation(); 
				} 
				else if (window.event) { 
					window.event.cancelBubble = true; 
				}
			})
			$("body").on("click",function(e){
				$(".search_result").hide();
				$(".searchForm").removeClass('is_show');
			})
			$(".searchArea").on("keyup",function(){
				var value=$.trim($(this).val());
				$(this).attr("actual_value",value);
				var search_info=$(this).parent().parent();
				var that=this;
				if(value==""){
					_this.loadhistory(search_info);
					search_info.find(".search_related").hide();
					search_info.find(".search_related_list").html("");
				}
				else{
					search_info.find(".search_related_list").html("");
					search_info.find(".search_history").hide();
					if((/^[A-Za-z0-9]+$/.test(value))){
						var keyword=value.substring(0,1);
						if(window.localStorage&&typeof window.localStorage.getItem('searchRelated')){
							var searchRelated=JSON.parse(window.localStorage.getItem('searchRelated'))||{};
							if(searchRelated&&searchRelated[keyword]){
								var c_time=new Date().getTime();
								var date3=c_time-searchRelated[keyword]['time'];
								var days=Math.floor(date3/(24*3600*1000));
								//1天内从缓存读取
								if(days<=1){
									_this.loadRelated(search_info,value,searchRelated[keyword]['list']);
									return false;
								}
							}
						}
						$.postAjax("/ajax/keywords",{'keywords':keyword},function(result){
							if(result&&result.length>0){
								var searchRelated=JSON.parse(window.localStorage.getItem('searchRelated'))||{};
								searchRelated[keyword]={"list":result,"time":new Date().getTime()};
								window.localStorage.setItem('searchRelated',JSON.stringify(searchRelated));
							}
							_this.loadRelated(search_info,value,result);
						});
					}
				}
			});
			$(".search_result").on("mouseout",function(){
				$(".searchArea").val($(".searchArea").attr("actual_value"));
			});
			if($("#currentkeyword").val()){
				_this.addHistory($("#currentkeyword").val());
			}
		},
		listEvent:function(){
			$(".c_keyword").on("mouseover",function(){
				$(".searchArea").val($(this).attr("keyword"));
			});
		},
		loadhistory:function(search_info){
			if(window.localStorage&&window.localStorage.getItem('search_history')){
	        	var search_history=JSON.parse(window.localStorage.getItem('search_history'));
		    }
		    else if($.getCookie('search_history')){
				var search_history=JSON.parse($.getCookie('search_history'))?JSON.parse($.getCookie('search_history')):[];
			}
			else{
				var search_history=[];
			}
			var length=search_history.length<=10?search_history.length:10;
    		if(length>0){
    			var value="";
        		var html="";
	        	for(var i=0;i<length;i++){
	        		value=$.trim(search_history[i]['keyword']);
	        		if(value){
	        			html+='<li><a keyword="'+value+'" class="c_keyword" href="/search?keyword='+value+'">'+value+'</a><span title="remove" class="c_remove search_history_remove" keyword="'+value+'">×</span></li>';
	        		}
	        	}
	        	search_info.find(".search_history_list").html(html).attr("load");
			    this.listEvent();
			    var width=search_info.width();
				search_info.find(".search_history").width(width).fadeIn();
    		}
    		else{
    			search_info.find(".search_history").html("").hide();
    		}
    		$(".search_history_remove").off("click").on("click",function(){
    			var keyword=$(this).attr("keyword");
    			$(this).parent().remove();
    			if(window.localStorage&&window.localStorage.getItem('search_history')){
	        		var search_history=JSON.parse(window.localStorage.getItem('search_history'));
		    	}
			    else if($.getCookie('search_history')){
					var search_history=JSON.parse($.getCookie('search_history'))?JSON.parse($.getCookie('search_history')):[];
				}
				else{
					var search_history=[];
				}
				$.each(search_history,function(k,list){
					if(list&&list['keyword']==keyword){
						search_history.splice(k,1);
					}
				});
				if(window.localStorage){
	            	try{
	            		window.localStorage.setItem('search_history',JSON.stringify(search_history));
	            	}
	            	catch(e){
	            		$.setCookie('search_history',JSON.stringify(search_history));
	            	}
	            }
	            else{
	            	$.setCookie('search_history',JSON.stringify(search_history));
	            }
    		});
		},
		loadRelated:function(search_info,keyword,result){
			var _this=this;
			var html="";
			var count=0;
			if(result){
				for(var i=0;i<result.length;i++){
					if(count>10){
						break;
					}
					else if(result[i]&&result[i].indexOf(keyword)==0){
						html+='<li><a keyword="'+result[i]+'" href="/search?keyword='+result[i]+'"" class="c_keyword">'+result[i]+'</a></li>';
						count++;
					}
				}
			}
			if(html){
				var width=search_info.width();
				search_info.find(".search_related_list").html(html);
				search_info.find(".search_related").width(width).fadeIn();
				_this.listEvent();
			}
			else{
				search_info.find(".search_related").hide();
				search_info.find(".search_related_list").html("");
			}
		},
		addHistory:function(keyword){
			if(keyword){
				if(window.localStorage&&window.localStorage.getItem('search_history')){
					var search_history=JSON.parse(window.localStorage.getItem('search_history'))?JSON.parse(window.localStorage.getItem('search_history')):[];
				}
				else if($.getCookie('search_history')){
					var search_history=JSON.parse($.getCookie('search_history'))?JSON.parse($.getCookie('search_history')):[];
				}
				else{
					var search_history=[];
				}
				var data={'keyword':keyword.toLowerCase()};
				var index=$.isInArray(search_history,"keyword",keyword);//判断是否已经在搜索记录中
		        //没有在记录中,置顶
	            if(index==-1){
	                if(search_history.length>=10){
	                    search_history.splice(9,search_history.length-9);
	                }
	                search_history.unshift(data);
	            }
	            else{
	                search_history.splice(index,1);//删除
	                search_history.unshift(data);//置顶
	            }
	            if(window.localStorage){
	            	try{
	            		window.localStorage.setItem('search_history',JSON.stringify(search_history));
	            	}
	            	catch(e){
	            		$.setCookie('search_history',JSON.stringify(search_history));
	            	}
	            }
	            else{
	            	$.setCookie('search_history',JSON.stringify(search_history));
	            }
			}
		}
	}
	return app;
});